package com.tanhua.admin.listeners;

import com.alibaba.fastjson.JSON;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.db.Log;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 1、类要交给容器管理
 * 2、配置方法，方法没有返回值，参数类型和发送消息的消息类型一致
 * 3、方法上配置注解，配置队列和交换机之间的绑定关系
 */
@Component
public class LogListener {

    @Autowired
    private LogMapper logMapper;

    /**
     * 获取消息，并且消费
     *  如何消费消息：就是构造数据保存到tb_log表中
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value=@Queue(
                        value = "tanhua.log.queue"//指定对类名称自己起的名字
                    ),
                    exchange=@Exchange(
                        value = "tanhua.log.exchange",//指定要发送的交换机名称
                        type = ExchangeTypes.TOPIC//交换机类型
                    ),
                    key="log.*"//处理类型
            )
    )
    public void log(String message) {
        System.out.println("获取到消息="+message);
        //1、json字符串转化为map对象
        Map<String,String> map = JSON.parseObject(message, Map.class);
        //2、获取属性
        String type = map.get("type");
        String logTime = map.get("logTime");
        String str = map.get("userId");
        Long userId = Long.valueOf(str);
        //3、写入到log对象中
        Log log = new Log();
        log.setLogTime(logTime);
        log.setType(type);
        log.setUserId(userId);
        //4、保存到数据库
        logMapper.insert(log);
    }
}
